﻿using System;
using System.Collections.Generic;
using System.ServiceModel.Channels;
using System.Web;
using System.Collections.Specialized;

namespace suanpan.API.Components.Core
{
    class RESTHighLowFormatter
    {
        public Message FormatMessage(ref Message requestMessage)
        {
            NameValueCollection QueryCol = new NameValueCollection();
            string newMethod = string.Empty;
            MessageHeaders headers = requestMessage.Headers;
            MessageProperties properties = requestMessage.Properties;
            HttpRequestMessageProperty requestMessageProperty = properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            string method = requestMessageProperty.Method;
            string querystring = requestMessageProperty.QueryString;

           if (querystring.ToLower().Contains(Constants.QueryStringParameters.METHOD))
                QueryCol = HttpUtility.ParseQueryString(querystring);
            if (QueryCol.Count > 0 && !string.IsNullOrEmpty(QueryCol[Constants.QueryStringParameters.METHOD]))
                newMethod = QueryCol[Constants.QueryStringParameters.METHOD];


            if (string.IsNullOrEmpty(newMethod) && requestMessageProperty.Headers[Constants.HttpHeaders.X_HTTP_METHOD_OVERRIDE_HEADER] != null)
            {
                newMethod = requestMessageProperty.Headers[Constants.HttpHeaders.X_HTTP_METHOD_OVERRIDE_HEADER];
            }
            switch (newMethod)
            {
                case Constants.HttpMethods.PUT:
                    requestMessageProperty.Method = Constants.HttpMethods.PUT;
                    break;
                case Constants.HttpMethods.DELETE:
                    requestMessageProperty.Method = Constants.HttpMethods.DELETE;
                    break;
                default:
                    break;
            }
            return requestMessage;
        }
    }
}
